package com.bosicen.crm.tools;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.google.gson.Gson;




/****
 * 常用的工具类
 * @author niyong
 *
 */
@SuppressWarnings("unchecked")
public class AppUtil {
	private static final Log log = LogFactory.getLog(AppUtil.class);
	private static MessageDigest digest = null;
	/****
	 * 密码的MD5转换
	 * @param data
	 * @return
	 */
	public synchronized static final String hash(String data) {
		if (digest == null) {
			try {
				digest = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException nsae) {
				System.err.println("Failed to load the MD5 MessageDigest. "
						+ "We will be unable to function normally.");
				nsae.printStackTrace();
			}
		}
		digest.update(data.getBytes());
		return encodeHex(digest.digest());
	}
	
	public static final String encodeHex(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		int i;

		for (i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString().toUpperCase();
	}
	
	
	
	 /*****
	  * 日期转换为字符串
	  * @param value
	  * @param type
	  * @return
	  */
	 public static String DateToString(Date value,String type){
		    SimpleDateFormat df = new SimpleDateFormat(type);
		    String str=null;
		    try{
		    	str=df.format(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    }
		 return str;
	 }
	 
	 /*****
	  * 字符串转换为日期
	  * @param value
	  * @param type
	  * @return
	  */
	 public static Date StringToDate(String value,String type){
		    SimpleDateFormat df = new SimpleDateFormat(type);
		    Date str=null;
		    try{
		    	str=df.parse(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    	
		    }
		 return str;
	 }
	 
	 /*****
	  * Long 类型转换
	  * @param obj
	  * @return
	  */
	 public static Long ObjectToLong(Object obj){
		 Long str=0L;
		 try{
			 if(AppUtil.ObjectToString(obj)!=null){
				 str=Long.parseLong(String.valueOf(obj).trim());
			 }
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return str;
		 
	 }
	 /*****
	  * Int 类型转换
	  * @param obj
	  * @return
	  */
	 public static int ObjectToInt(Object obj){
		 int str=0;
		 try{
			 if(AppUtil.ObjectToString(obj)!=null){
				 str=Integer.parseInt(String.valueOf(obj).trim());
			 }
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return str;
		 
	 }
	 /****
	  * String类型转换
	  * @param obj
	  * @return
	  */
	 public static String ObjectToString(Object obj){
		 
		String str=null;
		 try{
			 String str_=String.valueOf(obj);
			 if (StringUtils.isNotBlank(str_)&&!str_.equalsIgnoreCase("undefined")&&!str_.equalsIgnoreCase("null"))
				str=str_.trim();
			 
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return str;
	 }
	 /*****
	  * float 类型转换
	  * @param obj
	  * @return
	  */
	 public static float ObjectToFloat(Object obj){
		 float str=0;
		 try{
			 if(AppUtil.ObjectToString(obj)!=null){
				 str=Float.parseFloat(String.valueOf(obj).trim());
			 }
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return str;
		 
	 }
	 
	 
	 /**
	  * @description : double 类型转换
	  * @createTime  : 2010-8-5 上午11:22:00 
	  * @param obj
	  * @return  double
	  */
	 public static double ObjectToDouble(Object obj){
		 double value=0;
		 try{
			 if(AppUtil.ObjectToString(obj)!=null){
				 value=Double.parseDouble(String.valueOf(obj).trim());
			 }
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return value;
		 
	 }
	 
	 
	  /*****
		 * HTTP 请求
		 * @param urlString
		 * @return
		 * @throws IOException
		 */
		public static String sendHttp(String urlString) throws IOException{
			StringBuffer document=new StringBuffer();
			BufferedReader reader =null;
			try {
				log.info("HTTP_URL:"+urlString);
				URL url = new URL(urlString);
				URLConnection conn = url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(5000);
				 reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = null;
				while ( (line = reader.readLine()) != null) {
					document.append(line);
				}
				
			}catch (IOException ex) {
				System.out.println(ex.getMessage());
				return null;
			}finally{
				if(reader!=null) reader.close();
			}
			return 	document.toString();
		}
		
		
		/****
		 * 发送HTTP请求，返回XML
		 * @param xmlPath
		 * 返回方式为： <?xml version="1.0" encoding="utf-8" ?> 
						- <result>
							  <code>0</code> 
							  <message>查询信息成功</message> 
							- <info>
								  <succsum>1</succsum> 
								  <falsesum>2</falsesum> 
							  </info>
						</result>
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static  HashMap<String, Object>  sendHttpSinglon(String xmlPath){
			 HashMap<String, Object> hm=null;
			 log.info("url:"+xmlPath);
			 try {
				   SAXBuilder bSAX = new SAXBuilder(false);
				   Document doc=bSAX.build(new URL(xmlPath));
				   //Document doc=bSAX.build(new File(xmlPath));   
				   Element  root = doc.getRootElement();
				   List listmsg = root.getChildren();
				   if(listmsg.size()>0) hm=new HashMap<String, Object>();
				   for(int i=0;i<listmsg.size();i++){
					   Element catalog = (Element) listmsg.get(i);
					   hm.put(catalog.getName(), catalog.getText());
					   Iterator it=catalog.getChildren().iterator();
					   while(it.hasNext()){
						   Element child=(Element) it.next();
						   hm.put(child.getName(), child.getText());
					   }
				   }
				  
				 } catch (Exception e) {
				   e.printStackTrace();
				 } 
				return hm;
		}
		/*****
		 * 设置公用的分页参数
		 * @param request
		 * @return
		 */
		public static Page getPage(HttpServletRequest request,int pagesize){
			Page page=new Page();
			page.setCurrentPage(AppUtil.ObjectToInt(request.getParameter("pageno")));//页码
			int psize=AppUtil.ObjectToInt(request.getParameter("pagesize"));//每页数
			if(psize==0) psize=pagesize;
			page.setEveryPage(psize);
			return page;
		}
		/****
		 * 对于AJAX传输的中文进行URL的UTF-8解码
		 * @param str
		 * @return
		 */
		public static String URLDecoder2UTF8(String str){
			try{
			if(AppUtil.ObjectToString(str)!=null)
				str=URLDecoder.decode(str, "utf-8");
			
			}catch(Exception ex){
				ex.printStackTrace();
			}
			return str;
		}
		/***
		 * 对于AJAX传输的中文进行URL的UTF-8编码
		 * @param str
		 * @return
		 */
		public static String URLEncoder2UTF8(String str){
			try{
				if(AppUtil.ObjectToString(str)!=null)
					str=URLEncoder.encode(str,"UTF-8");
				
			}catch(Exception ex){
				ex.printStackTrace();
			}
			return str;
		}
		/****
		 * 返回当前日期
		 * @return
		 */
		public static String getcurrdate(){
			return AppUtil.DateToString(new Date(), "yyyy-MM-dd");
		}
		/****
		 * 返回当前日期
		 * @return
		 */
		public static String getcurrdateHours(){
			return AppUtil.DateToString(new Date(), "yyyy-MM-dd HH");
		}
		/****
		 * 返回当前日期
		 * @return
		 */
		public static String findcurrdate(){
			return AppUtil.DateToString(new Date(), "yyyyMMdd");
		}
		
		/***
		 * 获取IP
		 * @param request
		 * @return
		 */
		public static 	String getIP(HttpServletRequest request){
			String ip = request.getHeader("x-forwarded-for");
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("WL-Proxy-Client-IP");
	        }
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	       }
	    
	        return ip;
		}
		/*****
		 * 去掉电话号码的-号
		 * @param t
		 * @return
		 */
		public static String checkTelNum(String t){
			t=AppUtil.ObjectToString(t);
			if(t!=null){
				if(t.length()>=7)
				    t=t.substring(0, 7).replace("-", "")+t.substring(7,t.length());
			}
			return t;
		}

		
		/****
		 * 查询出来的进行处理
		 * @param str
		 * @return
		 */
		public static String toTextAreaValue(String str) {
			if (str != null) {
				str = str.replaceAll("\r", "").replaceAll("\n", "").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("<br/>", "\n").replaceAll(
						"&amp;", "&").replaceAll("&nbsp;", " ");
				return str;
			}
			return "";
		}
		
		/**
		 * @description : 按照四舍五入的方法取double数字的精度， 并以字符串的形式返回。 
		 * @createTime  : 2010-8-3 下午12:01:19 
		 * @author      : wangguodong
		 * @param value 要取精度的值
		 * @param scale 精度的小数位数
		 * @return  double
		 */
		public static String roundHalfUp(double value, int scale){
			BigDecimal bd = new BigDecimal(value);
			bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
			String formatStr="0";
			for(int i=0; i<scale; i++){
				if(i==0){
					formatStr = formatStr + ".0";
				} else {
					formatStr = formatStr + "0";
				}
				
			}
			double newValue = bd.doubleValue();
			String formatValue = new DecimalFormat(formatStr).format(newValue);
			return formatValue;
		}
		/****
		 * 获取订单号  20100060001 ~ 20100069999
		 * @param count
		 * @return
		 */
		public static String findorderno(int count){
			++count;
			String orderno=AppUtil.findcurrdate();
			if(0<=count&&count<10){orderno+="000"+count;}
			if(10<=count&&count<100){orderno+="00"+count;}
			if(100<=count&&count<1000){orderno+="0"+count;}
			if(1000<=count&&count<10000){orderno+=count;}
			return orderno;
		}
		
		//main
		public static void main(String[] args) throws Exception {
			 System.out.println(AppUtil.hash("123"));
		}
		
}
